package odnoklassniki;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import musictrackrecommendation.DatabaseDataset;
import musictrackrecommendation.Dataset;
import musictrackrecommendation.ExperimentParameters;

import randomwalk.Submatrix;

public class OdnoklassnikiTrackTrackSubmatrix extends Submatrix {

	private static final String TRACK1_ID = "track1_id";
	private static final String TRACK2_ID = "track2_id";
	
	public OdnoklassnikiTrackTrackSubmatrix() throws ClassNotFoundException,
			SQLException {
		super();
	}

	public OdnoklassnikiTrackTrackSubmatrix(int[] rowIds, int[] columnIds,
			double[] values, double[] transponedValues) {
		super(rowIds, columnIds, values, transponedValues);
	}

	@Override
	public String getColumnFieldName() {
		return TRACK2_ID;
	}

	@Override
	public String getOrderFieldName() {
		return OdnoklassnikiDataset.ID_ATTRIBUTE;
	}

	@Override
	public String getRowFieldName() {
		return TRACK1_ID;
	}

	@Override
	public int getSubmatrixSize() {
		ExperimentParameters parameters = ExperimentParameters.getInstance();		
		Dataset datasetProperties = parameters.getDatasetProperties();
		return datasetProperties.getTrackTrackCount();
	}

	@Override
	public double[] getSubmatrixValues(int[] columnIds) {
		double[] similarity = new double[columnIds.length];
		try {
			ExperimentParameters parameters = ExperimentParameters.getInstance();
			DatabaseDataset datasetDatabase = parameters.getDatasetDatabase();
			
			Class.forName(datasetDatabase.getJdbcDriverName());

	        Connection con =
	                DriverManager.getConnection(
	                		datasetDatabase.getJdbcConnectionUrl(),
	                		datasetDatabase.getDatabaseUser(), 
	                		datasetDatabase.getPassword());

			Statement stmt = con.createStatement();
			String query = "select similarity from " 
				+ OdnoklassnikiDataset.TRACK_TRACK_TABLE_NAME 
				+ " order by id";
			ResultSet rs = stmt.executeQuery(query);

			int rowNumber = 0;
			while (rs.next()) {
				 similarity[rowNumber] = rs.getDouble(1);
				rowNumber++;
			}
			rs.close();
			con.close();
		} catch (ClassNotFoundException e) {
			System.out.println("Cannot register JDBC driver");
			e.getMessage();
		} catch (SQLException e) {
			System.out.println("Cannot retrieve data from database");
			e.getMessage();
		}
		return similarity;
	}

	@Override
	public String getTableName() {
		return OdnoklassnikiDataset.TRACK_TRACK_TABLE_NAME;
	}

}
